/**
 * 这里是定义和用户相关的路由处理函数，供 /router/user 调用
 */
// 数据库操作
// const mysql = require('mysql');
// const moduleDB = require('../db/index')  // 引入数据模型
// 生成 token 的包
const jwt = require('jsonwebtoken')
// 导入jwt的配置文件
const config = require('../config')
// 数据库操作
const sequelize = require('../db/dbconfig');
const UserModel = require('../db/models/users');
const userModel = UserModel(sequelize);
const jwtConfig = require('../config')
const jwtEn = require("jwt-simple");




// 连接数据库
// const conn = mysql.createConnection(moduleDB.mysql);
// conn.connect();

// 用户注册函数
exports.regUser = async (req, res) => {
  // 接收 body
  try {
    const userinfo = req.body
    if(req.session.captcha !== req.body.captcha || req.body.captcha === undefined) return  res.myMsg('验证码输入错误，请重新输入!',403)
    let is_exist = await userModel.findAll({
      attributes: ['user_id'],
      where: {
        username: userinfo.username
      }
    })
    if(is_exist[0]) return res.myMsg('用户名已存在')
    if(userinfo.password !== userinfo.password2) return res.myMsg('两次输入的密码不一致')
    let userNickname = 'user' + Math.floor(Math.random()*9000+1000)
    let results = await userModel.create({
      username: userinfo.username,
      password: userinfo.password,
      nickname: userNickname,
      // email: userinfo.email,
      permissions: 1
    })
    if(!results) return res.myMsg('服务器内部错误，注册失败')
    res.myMsg(results,200)
  } catch(e) {
    if(e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg('服务器内部错误',500)
    // res.send(e)
  }


  // res.myMsg(results,0)
  // const sql = 'select user_id from users where username = ?'
  // conn.query(sql, userinfo.username, (err, results) => {
  //   if(err) return res.myMsg(err)
  //   if(results.length > 0) {
  //     return res.myMsg('用户名已存在! 请更换其他用户名')
  //   }
  //   let userNickname = 'user' + Math.floor(Math.random()*9000+1000)
  //   // console.log(userNickname)
  //   // console.log(userinfo)
  //   const sql = 'INSERT INTO users(`username`, `password`, `nickname`, `email`, `permissions` ) VALUES(?, ?, ?, ?, 1);'
  //   conn.query(sql, [userinfo.username, userinfo.password, userNickname, userinfo.email], (err, results) => {
  //     if(err) return res.myMsg(err)
  //     if(results.affectedRows !== 1) return res.myMsg('用户注册失败')
  //     res.myMsg('用户注册成功')
  //   })
  //
  // })
}

// 用户登录函数
exports.loginUser = async (req, res) => {
  // console.log(req.session.captcha)
  // console.log(req.body.captcha)
  if(!req.body.isCaptcha) {
    console.log(req.session.captcha,req.body.captcha)
    if(req.session.captcha !== req.body.captcha || req.body.captcha === undefined) return  res.myMsg('验证码输入错误，请重新输入!',403)
  }
  try {
    const userinfo = req.body
    let results = await userModel.findAll({
      attributes: ['user_id', 'username', 'password', 'nickname', 'email', 'sex', 'user_pic', 'permissions', 'is_ban', 'is_delete'],
      where: {
        username: userinfo.username,
        password: userinfo.password
      }
    });
    if(!results[0]) return  res.myMsg('用户名或密码错误，登录失败')
    // const avatar = results[0].user_pic
    // const avatar = 'http://127.0.0.1:3000/uploads/avatar/default_svg.svg'
    const avatar = 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
    const user = { ...results[0].dataValues, password: ''}
    const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
    // const token = 'Bearer ' + tokenStr
    // 调用 res.send() 将 Token 响应给客户端
    res.header("Authorization",tokenStr)
    res.send({
      // data: token,
      status: 200,
      code: 200,
      // statusTest:'管理员登录成功',
      message: '登录成功',
      token: 'Bearer ' + tokenStr,
    })
  } catch(e) {
    if(e.name === 'SequelizeValidationError') return res.myMsg(e)
    res.myMsg(e,500)
  }

  // res.myMsg(results,0)

  // const sql = 'select username, password, nickname, email, sex, permissions, is_ban, is_delete from users where username = ?'
  // conn.query(sql, [userinfo.username], (err, results) => {
  //   if(err) return res.myMsg(err)
  //   if(results.length !== 1) return res.myMsg('用户名或密码错误')
  //   // 判断密码是否正确
  //   const compareResult = userinfo.password === results[0].password
  //   if(!compareResult) return res.myMsg('用户名或密码错误')
  //
  //   const user = { ...results[0], password: ''}
  //   const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
  //   // 调用 res.send() 将 Token 响应给客户端
  //   res.send({
  //     status: 0,
  //     message: '登录成功',
  //     token: 'Bearer ' + tokenStr,
  //   })
  // })

  // userModel.findAll({
  //   attributes: ['username', 'password', 'nickname'],
  //   where: {
  //     username: 'admin'
  //   }
  // }).then(results => {
  //   res.json({results})
  // });

  // var results = await userModel.findAll({
  //   attributes: ['user_id', 'username', 'password', 'nickname'],
  //   // where: {
  //   //   username: 'admin'
  //   // }
  //   // order: [['user_id','DESC']]
  // });
  // res.send({results})

}

// 获取用户信息
exports.getUserinfo = async (req, res) => {
  try {
    // console.log(tokenStr)
    let jwtEn = require('jwt-simple');
    let tokenStr = req.headers.authorization.slice(7)
    // console.log('req.headers',req.headers)
    // let {token} = req.body
    // const usermessage = token.slice(7)
    const PRIVATE_KEY = jwtConfig.jwtSecretKey
    const decodeToken  = jwtEn.decode(tokenStr, PRIVATE_KEY)
    res.send({
      message: '请求成功!',
      data: decodeToken
    })
  }catch (e) {
    // console.log(e)
    res.myMsg(e,500)
  }
}

// 用户退出登录
exports.logout = async (req, res) => {
  req.params.auth = ''
  res.send({
    status: 200,
    message: '退出登录成功!'
  })
}
